const { Service } = require('egg');
const { raw } = require('mysql2');

class TopicLessonService extends Service {

    async list(topicId) {
        const { ctx } = this;
        let queryOptions = {};

        if (topicId) {
            queryOptions.where = { topicId };
        }

        return ctx.model.TopicLesson.findAll(queryOptions);
    }


    async id(id) {
        const { ctx } = this;
        console.log("id", id)
        return ctx.model.TopicLesson.findByPk(id);
    }

    async create(data) {
        return this.ctx.model.TopicLesson.create(data);
    }

    async delete(id) {
        const { destroyedCount } = await this.ctx.model.TopicLesson.destroy({
            where: { id },
        });

        return destroyedCount;
    }

    async update(id, updateData) {
        const [affectedCount] = await this.ctx.model.TopicLesson.update(updateData, {
            where: { id },
        });

        if (affectedCount === 0) {
            throw new Error('没有找到匹配的记录进行更新');
        }

        return affectedCount;
    }

    async updateCertificateActive(key) {

        let myId = this.ctx.helper.toInt(key)

        const configInfo = await this.app.model.CertificateConfig.findOne({
            where: { id: myId },
            raw: true,
        });
        if (configInfo) {
            const { id, updateInfo } = configInfo
            await this.app.model.CertificateConfig.update({
                ...updateInfo,
                isActive: 1,
            }, {
                where: { id },
            });
        }
    }
}

module.exports = TopicLessonService;